import config from '@/common/config.js'
//  初始化请求配置
const settingApp = (vm) => {
	//初始化模板变量
	vm.config.globalProperties.$arrayGroup = (array, subGroupLength) => {
		let index = 0;
		let newArray = [];
		while (index < array.length) {
			newArray.push(array.slice(index, index += subGroupLength));
		}
		return newArray;
	}

	//初始化模板变量
	vm.config.globalProperties.$arrayBufferToBase64 =(buffer) =>{
	  var binary = ''
	  var bytes = new Uint8Array(buffer)
	  var len = bytes.byteLength
	  for (var i = 0; i < len; i++) {
		binary += String.fromCharCode(bytes[i])
	  }
	  return window.btoa(binary)
	}

	//初始化模板变量
	const tempDataInit = function(temp, obj, item) {
		for (let key in temp) {

			let value_type = typeof temp[key]
			let value = item[key];
			let default_value = undefined
			// console.log(key,value)

			if (temp[key] instanceof Object) {
				var jsonObject = JSON.stringify(temp[key])
				if (jsonObject[0] === '[') {
					default_value = []
				} else if (jsonObject[0] === '{') {
					value = Object.assign({}, value || {})
					let tempObj = tempDataInit(temp[key], Object.assign({}, obj[key] || {}), value);
					if (Object.keys(tempObj).length) {
						default_value = tempObj
						value = tempObj
					} else {
						default_value = Object.assign({}, temp[key] || {})
					}
				} else {
					default_value = ""
				}
			} else if (value_type === 'string') {
				default_value = temp[key] + ''
				value = (value || '') + ""
			} else if (value === 0) {
				default_value = temp[key] || 0
			}
			obj[key] = value || default_value
		}
		return obj;
	}
	vm.config.globalProperties.$tempDataInit = tempDataInit

	vm.config.globalProperties.$get7Day = function(temp, obj, item) {

		let weekday = new Array(7)
		weekday[0] = '星期日'
		weekday[1] = '星期一'
		weekday[2] = '星期二'
		weekday[3] = '星期三'
		weekday[4] = '星期四'
		weekday[5] = '星期五'
		weekday[6] = '星期六'

		const data = [];
		const formatDate = (date, i) => {
			// 取出当前是星期几
			let day = date.getDay();
			let weedayDesc = weekday[day]
			if (i == 0) {
				weedayDesc = "今天"
			} else if (i == 1) {
				weedayDesc = "明天"
			} else if (i == 2) {
				weedayDesc = "后天"
			}
			const monthDay = formatZero(date.getMonth() + 1) + '-' + formatZero(date.getDate());
			data.push({
				day: monthDay,
				date: date.getFullYear() + '-' + monthDay,
				weekday: weedayDesc,
				weekend: [0, 6].indexOf(day) > -1
			})
		}

		for (let i = 0; i < 7; i++) {
			const date = new Date()
			date.setDate(date.getDate() + i)
			formatDate(date, i)
		}

		return data;

	}

	const formatZero = function(num) {
		const number = parseInt(num);
		return (number < 10 && number >= 0 ? '0' : '') + number;
	}

	vm.config.globalProperties.$formatTime = function(time, format = "", step = 0) {
		var timeFormat = !format ? "YYYY-MM-DD HH:mm:ss" : format
		var date = new Date()

		if (time === 'month01') {
			date = new Date(date.getFullYear(), date.getMonth())
		} else if (time === 'nextDay') {
			date = new Date()
			date.setTime(date.getTime() + 86400 * 1000 * step)
		} else if (parseInt(time) > 0) {
			date.setTime(time * 1000)
		}

		const year = date.getFullYear() + '';
		const month = formatZero(date.getMonth() + 1);
		const day = formatZero(date.getDate());
		const hour = formatZero(date.getHours());
		const minute = formatZero(date.getMinutes());
		const second = formatZero(date.getSeconds());

		if (timeFormat.indexOf('YYYY') > -1) {
			timeFormat = timeFormat.replace('YYYY', year)
		}
		if (timeFormat.indexOf('MM') > -1) {
			timeFormat = timeFormat.replace('MM', month)
		}
		if (timeFormat.indexOf('DD') > -1) {
			timeFormat = timeFormat.replace('DD', day)
		}
		if (timeFormat.indexOf('HH') > -1) {
			timeFormat = timeFormat.replace('HH', hour)
		}
		if (timeFormat.indexOf('mm') > -1) {
			timeFormat = timeFormat.replace('mm', minute)
		}
		if (timeFormat.indexOf('ss') > -1) {
			timeFormat = timeFormat.replace('ss', second)
		}

		return timeFormat
	}

	//添加网络请求插件
	const $network = function(api, params = {}, options = {}, method = "post") {
		return new Promise((resolve, reject) => {
			uni.$uv.http[method](api, params, !(options instanceof Function) ? options : {
				custom: {
					completeFnc: (res) => {
						options(res)
					}
				}
			}).then(res => {
				resolve(res)
			}).catch(err => {
				reject(err)
			})
		})
	}
	uni.$network = $network
	vm.config.globalProperties.$network = $network
	vm.config.globalProperties.$baseURL = config.network.baseURL


	//页面跳转
	vm.config.globalProperties.$multiRedirect = function(url, loginState) {
		console.log('>>>>>>>>>>>>$multiRedirect', url)
		if (loginState === true) {
			if (!this.vuex_user_id) {
				uni.$emit('loginEvent')
				return
			}
		}
		if (url === -1) {
			uni.navigateBack()
		} else if (url && url.length > 0) {
			console.log('+++++', url.indexOf('http'))
			if (url.indexOf('http') === 0) {
				// #ifdef H5 
				location.href = url
				// #endif
				// #ifdef MP-WEIXIN
				uni.navigateTo({
					url: '/pages/web/web?url=' + encodeURIComponent(url)
				})
				// #endif
				// #ifdef APP-PLUS
				plus.runtime.openURL(url, function(res) {
					console.log(res);
				});
				// #endif
			} else if (url.indexOf('&switch') > -1) {
				uni.switchTab({
					url
				})
			} else {
				uni.navigateTo({
					url
				})
			}
		}
	}
	//拨打电话
	vm.config.globalProperties.$makePhoneCall = function(tel, location_id = 0) {
		console.log("makePhoneCall", tel)
		if (tel == 110) {
			uni.showModal({
				content: '立即报警?',
				success: function(res) {
					if (res.confirm) {
						uni.$uv.http.post('/api/index/call', {
							location_id: location_id
						}).then((res) => {

						}).catch((err) => {
							console.log(err)
						})
						uni.makePhoneCall({
							phoneNumber: tel + '',
							success() {
								console.log('success')
							},
							fail() {
								console.log('fail')
							}
						})
					} else if (res.cancel) {
						console.log('用户点击取消');
					}
				}
			});
		} else {
			uni.makePhoneCall({
				phoneNumber: tel + '',
				success() {
					console.log('success')
				},
				fail() {
					console.log('fail')
				}
			})
		}




	}

	// Copy
	vm.config.globalProperties.$setClipboard = function(content) {

			uni.setClipboardData({
				data: content,
				success: function() {
					uni.$uv.toast('复制成功')
				}
			});
		},

		//showModal
		vm.config.globalProperties.$showModal = function(json) {
			return uni.showModal(Object.assign({
				success: (res) => {


				}
			}, json))
		}

	//json
	vm.config.globalProperties.$jsonToQuery = function(json) {
		let query = ''
		Object.keys(json).map(function(key) {
			query += key + '=' + json[key] + '&'
		})
		console.log(query)
		return query.length > 0 ? query.substring(0, query.length - 1) : query;
	}
	//json
	vm.config.globalProperties.$previewImage = function(img) {
		let showImages = [img]
		if (img instanceof Array) {
			showImages = img;
		}
		uni.previewImage({
			urls: showImages,
		});
	}

	vm.config.globalProperties.$weixin_qrcodeQueryString = function(url, name) {
		var reg = new RegExp('(^|&|/?)' + name + '=([^&|/?]*)(&|/?|$)', 'i')
		var r = url.substr(1).match(reg)
		if (r != null) {
			return r[2]
		}
		return null;
	}


	/*
	获取缓存数据-有就读取,没有 就网络请求
	obj-对象格式  {"数据类型":"缓存的键名"}
		获取商品分类 可使用 {goods_cate:goodsCateList}
	*/

	vm.config.globalProperties.$getCacheData = (function() {
		const cacheConfing = {}
		return function(obj, fnc, refresh) {
			const forceRefresh = refresh === true
			if (!(fnc instanceof Function) || !(obj instanceof Object)) {
				return
			}
			let query = {}
			let results = {};
			if (forceRefresh) {
				query = obj
			} else {
				Object.keys(obj).map(function(key) {
					const valueKey = obj[key]
					if (!cacheConfing[valueKey]) {
						query[key] = valueKey
					} else {
						//绑定缓存数据
						results[valueKey] = cacheConfing[valueKey]
					}
				})

			}

			if (!Object.keys(query).length) {
				//返回数据
				fnc(results)
			} else {
				$network('/api/index/groupData', query).then((res) => {
					const data = res.data || {}

					Object.keys(data).map(function(key) {
						const value = data[key];
						results[key] = value;
						cacheConfing[key] = value;
					})
					//返回数据
					fnc(results)
				})
			}



		}
	})()



	vm.config.globalProperties.$timeForMat = (count, currentTime, mode = 'after') => {
		// 拼接时间
		let time1 = new Date()
		if (currentTime) {
			const defaultYear = uni.$uv.timeFormat(currentTime, 'yyyy');
			const defaultMonth = uni.$uv.timeFormat(currentTime, 'mm');
			const defaultDay = uni.$uv.timeFormat(currentTime, 'dd');
			time1 = new Date(defaultYear, defaultMonth - 1, defaultDay)
		}

		if (mode == 'after') {
			time1.setTime(time1.getTime() + (24 * 60 * 60 * 1000))
		} else {
			time1.setTime(time1.getTime() - (24 * 60 * 60 * 1000))
		}
		let Y1 = time1.getFullYear()
		let M1 = ((time1.getMonth() + 1) >= 10 ? (time1.getMonth() + 1) : '0' + (time1.getMonth() + 1))
		let D1 = (time1.getDate() >= 10 ? time1.getDate() : '0' + time1.getDate())
		let timer1 = Y1 + '-' + M1 + '-' + D1 // 当前时间
		let time2 = new Date()
		if (currentTime) {
			const defaultYear = uni.$uv.timeFormat(currentTime, 'yyyy');
			const defaultMonth = uni.$uv.timeFormat(currentTime, 'mm');
			const defaultDay = uni.$uv.timeFormat(currentTime, 'dd');
			time2 = new Date(defaultYear, defaultMonth - 1, defaultDay)
		}

		if (mode == 'after') {
			time2.setTime(time2.getTime() + (24 * 60 * 60 * 1000 * count))
		} else {
			time2.setTime(time2.getTime() - (24 * 60 * 60 * 1000 * count))
		}
		let Y2 = time2.getFullYear()
		let M2 = ((time2.getMonth() + 1) >= 10 ? (time2.getMonth() + 1) : '0' + (time2.getMonth() + 1))
		let D2 = (time2.getDate() >= 10 ? time2.getDate() : '0' + time2.getDate())
		let timer2 = Y2 + '-' + M2 + '-' + D2 // 之前的7天或者30天
		return {
			t1: timer1,
			t2: timer2
		}
	}

	//小程序二维码参数解析
	vm.config.globalProperties.$mpSceneDecode = (content) => {
		const scene = decodeURIComponent(content)
		var _str = scene + "";
		var _str_list = _str.split("&");
		var res = {};
		for (var i in _str_list) {
			var _tmp_str = _str_list[i];
			var _tmp_str_list = _tmp_str.split("=");
			if (_tmp_str_list.length > 0 && _tmp_str_list[0]) {
				res[_tmp_str_list[0]] = _tmp_str_list[1] || null;
			}
		}
		return res;
	}
	//小程序二维码参数解析
	vm.config.globalProperties.$date2Week = (date) => {
		if (!date) {
			return '';
		}
		var weekday = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
		var f = new Date(date);
		var week = f.getDay(); //计算出星期几
		return weekday[week];
	}
	//小程序二维码参数解析
	vm.config.globalProperties.$parseUrlParams = (content) => {
		var _str = content + "";
		var _str_list = _str.split("&");
		var res = {};
		for (var i in _str_list) {
			var _tmp_str = _str_list[i];
			var _tmp_str_list = _tmp_str.split("=");
			if (_tmp_str_list.length > 0 && _tmp_str_list[0]) {
				res[_tmp_str_list[0]] = _tmp_str_list[1] || null;
			}
		}
		return res;
	}

	//小程序打开地图
	vm.config.globalProperties.$openLocation = (params = {}) => {
		uni.openLocation(Object.assign({
			success: function() {
				console.log('success');
			},
			fail: function(err) {
				console.log('err',params);
				uni.$uv.toast('err:' + JSON.stringify(err))
				console.log('err', err);
			}
		}, params));
	}

}
export {
	settingApp
}